package controller;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;
import model.UsersManager;
import exciptions.UserNotExistExcitpion;

/**
 * Servlet implementation class UsersServlet
 */
@WebServlet("/UsersServlet")
public class UsersServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UsersServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		String pass = request.getParameter("password");
		PrintWriter printWriter = response.getWriter();

		HttpSession ses = request.getSession();
		int chance;
		
		try{
			chance =(int) ses.getAttribute("tries");
		}catch(NullPointerException n){
			ses.setAttribute("tries", 1);
			chance =1;
		}

		
		ServletContext con = getServletContext();
		UsersManager users = (UsersManager) con.getAttribute("users");
		
		
		if (users ==null){
		users = new UsersManager();
		con.setAttribute("users", users);
		}
		
		
		
		User user;
		int i= 0;
		if (login != null &&  pass != null){
			try {
				user = users.getUser(login, pass);
				//printWriter.println(user.toString());
				request.setAttribute("user", user);
				request.getRequestDispatcher("welcome.jsp").forward(request, response);
			} catch (UserNotExistExcitpion e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				chance++;
				ses.setAttribute("tries", chance);
				
				if (chance >3){
					ses.removeAttribute("tries");
					printWriter.println("You have to register first to access in the system");
					request.setAttribute("user", new User (login));
					request.getRequestDispatcher("register.jsp").include(request, response);
				}
				else{
					printWriter.println(e.getMessage());
					request.getRequestDispatcher("index.jsp").include(request, response); 
				}
				
			}
			
		}
		else {
			
			printWriter.println("No information entered");
		}
	}
		
		
		
	

}
